﻿using SK3000RunningTestTool.SKServerDelegate;
using SK3000RunningTestTool.SKServerDelegate.Value;
using SK3000RunningTestTool.SKServerEnum;
using SK3000RunningTestTool.SKServerSource;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SK3000RunningTestTool.SKService
{
    public class Service_MonitorService : ISKService
    {
        public const string c_strCmd = "$request&serverstatus&local";


        public SKServer Server
        {
            get;
            set;
        }



        public int ID
        {
            get;
            set;
        }
        private Enum_ServiceTestType typeID = Enum_ServiceTestType.MonitorService;
        /// <summary>
        /// 类型ID
        /// </summary>
        public Enum_ServiceTestType TypeID
        {
            get { return typeID; }
            set { }
        }
        public ServiceTestType Type => ServiceTestTypeSource.ServiceTestTypeList[typeID];
        string strServiceName = "主备监控服务";
        public string ServiceName
        {
            get { return strServiceName; }
            set { strServiceName = value; }
        }

        public string ServiceRemark
        {
            get;
            set;
        }
        public string ServiceAddress
        {
            get;
            set;
        }

        public ushort ServicePort
        {
            get;
            set;
        }

        public object Tag
        {
            get;
            set;
        }

        public event ServiceTestProgressDelegate ServiceTestProgressEvent;

        private void ServiceTestProgress(ServiceTestProgressValue value)
        {
            if (ServiceTestProgressEvent != null)
            {
                ServiceTestProgressEvent(this, value);
            }
        }



        public event ServiceTestCallbackDelegate ServiceTestCallbackEvent;

        public void ServiceTestCallback(ServiceTestCallbackValue value)
        {
            if (ServiceTestCallbackEvent != null)
            {
                ServiceTestCallbackEvent(this, value);
            }
        }


        public event MonitionService_ReceiveServerStatausDelegate MonitionService_ReceiveServerStatausEvent;

        private void MonitionService_ReceiveServerStataus(MonitionService_ReceiveServerDataValue MonitionService_ReceiveServerDataValue)
        {
            if (MonitionService_ReceiveServerStatausEvent != null)
            {
                MonitionService_ReceiveServerStatausEvent(this, MonitionService_ReceiveServerDataValue);
            }
        }

        /// <summary>
        /// 服务器测试 
        /// </summary>
        /// <returns></returns>
        public ServiceTestCompleteValue ServiceTest()
        {
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ServiceTestStart });
            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 0 });
            ServiceTestCompleteValue result = new ServiceTestCompleteValue
            {
                reuslt = Enum_ServiceTestResult.Fail,
            };
            //1.向指定端口发送数据
            //2.等待数据返回
            //3.解析返回数据
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ServiceAddress), ServicePort);
            //定义网络类型，数据连接类型和网络协议UDP
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            server.Bind(new IPEndPoint(IPAddress.Any, 0));
            byte[] connectData = Encoding.UTF8.GetBytes(c_strCmd);
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.SendTestDataing });
            server.SendTo(connectData, connectData.Length, SocketFlags.None, ip);
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.SendTestDataSuccess });
            ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ReceiveDataing });
            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 30 });
            byte[] array = new byte[1024];
            EndPoint endPoint = ip;
            server.ReceiveTimeout = 10000; //10秒超时
            try
            {
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 40 });
                int num = server.ReceiveFrom(array, ref endPoint);
                byte[] bytsValue = GetValue(array, num);
                ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.ReceiveDataSuccess });
                string content = Encoding.UTF8.GetString(bytsValue);
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 60 });
                Analysis(content);
                result.reuslt = Enum_ServiceTestResult.Normal;//只要收到数据,即认为是正常
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 90 });
            }
            catch
            {
                //超时 异常
                ServiceTestCallback(new ServiceTestCallbackValue { EventValue = Enum_ServiceTestEvent.SendTestDataException });
                ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 95 });
            }
            server.Dispose();
            ServiceTestProgress(new ServiceTestProgressValue { ProgressValue = 100 });
            return result;
        }
        public void ServiceTestAsync(ServiceTestCompleteDelegate callback)
        {
            Timer timTimeOutVideoClose = new Timer(new TimerCallback(timTimtOutVideoClose_Event), callback, 0, Timeout.Infinite);
            return;
        }

        private void timTimtOutVideoClose_Event(object sender)
        {
            ServiceTestCompleteValue value = ServiceTest();
            ServiceTestCompleteDelegate call = (ServiceTestCompleteDelegate)sender;
            if (call != null)
            {
                call(this, value);
            }
        }

        private byte[] GetValue(byte[] bytsValue, int length)
        {
            byte[] result = new byte[length];
            for (int i = 0; i < length; i++)
            {
                result[i] = bytsValue[i];
            }
            return result;
        }

        /// <summary>
        /// 数据解析
        /// </summary>
        /// <param name="strContent"></param>
        /// <returns></returns>
        private bool Analysis(string strContent)
        {
            bool bolResult = false;
            string[] Temp_strsContent = strContent.Split('&');
            switch (Temp_strsContent[0])
            {
                case "$serverstatus":
                    Analysis_serverstatus(Temp_strsContent[1]);
                    break;
            }
            return bolResult;
        }



        /// <summary>
        /// 数据解析_服务器状态
        /// </summary>
        /// <param name="strServerStatus"></param>
        /// <returns></returns>
        public bool Analysis_serverstatus(string strServerStatus)
        {
            bool bolResult = false;
            MonitionService_ReceiveServerStataus(new MonitionService_ReceiveServerDataValue
            {
                ServerStatus = Convert.ToInt32(strServerStatus)
            });
            return bolResult;
        }
    }
}
